//
//  BCNewsViewController.m
//  BCVersion
//
//  Created by 吴 崧 on 14-2-25.
//  Copyright (c) 2014年 Jungle. All rights reserved.
//

#import "BCNewsViewController.h"
#import "BCNetworkClient.h"
#import "BCAdItemViewController.h"
#import "BCLoginViewController.h"
#import "BCProgressHUD.h"

@interface BCNewsViewController () <UIPageViewControllerDataSource, UIPageViewControllerDelegate>
@property (nonatomic, strong) UIPageViewController *bannerPageViewController;
@property (nonatomic, strong) NSMutableArray *banners;
@property (nonatomic, strong) NSMutableArray *bannerViewControllers;
@property (nonatomic, strong) NSMutableArray *ads;
@property (nonatomic, strong) NSMutableArray *adViewControllers;
@end

@implementation BCNewsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	if (self) {
		// Custom initialization
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
	self.banners = [NSMutableArray array];
	self.bannerViewControllers = [NSMutableArray array];
    
    self.ads = [NSMutableArray array];
	self.adViewControllers = [NSMutableArray array];
    
    [BCProgressHUD showWithTile:@"下载中" animated:YES];
    
#if BCM_VERSION
    [BCNetworkClient merchantbanner:0
#else
     [BCNetworkClient zixunbanner:0
      
#endif
                            limit:0
                          success: ^(NSNumber *total, NSString *type, NSArray *ads) {
                              if (total.intValue > 0) {
                                  self.bannerPageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
                                  
                                  
                                  self.bannerPageViewController.delegate = self;
                                  self.bannerPageViewController.dataSource = self;
                                  
                                  self.bannerPageViewController.view.frame = self.bannerView.bounds;
                                  
                                  [self.bannerView addSubview:self.bannerPageViewController.view];
                              }
                              [self.banners addObjectsFromArray:ads];
                              
                              [ads enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
                                  UIViewController *vc = [[BCAdItemViewController alloc] initWithTitle:obj[@"title"] message:obj[@"message"] imageUrl:obj[@"image"] size:self.bannerView.frame.size];
                                  
                                  [self.bannerViewControllers addObject:vc];
                              }];
                              
                              if (self.bannerViewControllers.count > 0) {
                                  [self.bannerPageViewController setViewControllers:@[self.bannerViewControllers[0]] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion: ^(BOOL finished) {
                                  }];
                              }
                              
                              self.bannerPageControl.numberOfPages = self.bannerViewControllers.count;
                              
#if BCM_VERSION
                              [BCNetworkClient merchant:0
#else
                               [BCNetworkClient zixunAds:0
#endif
                                                   limit:0
                                                 success: ^(NSNumber *total, NSString *type, NSArray *ads){
                                                     [self.ads addObjectsFromArray:ads];
                                                     
                                                     [ads enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
                                                         UIViewController *vc = [[BCAdItemViewController alloc] initWithTitle:obj[@"title"] message:obj[@"message"] imageUrl:obj[@"image"] size:CGSizeMake(217, 101)];
                                                         
                                                         [self.adViewControllers addObject:vc];
                                                     }];
                                                     
                                                     
                                                     __block CGFloat left1 = 0;
                                                     __block CGFloat left2 = 0;
                                                     
                                                     __block int count1 = 0;
                                                     __block int count2 = 0;
                                                     
                                                     [self.adViewControllers enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
                                                         UIViewController *vc = obj;
                                                         
                                                         if (idx <= self.adViewControllers.count / 2) {
                                                             vc.view.frame = CGRectSetX(vc.view.frame, left1);
                                                             
                                                             [self.scrollView1 addSubview:vc.view];
                                                             left1 += 217 + 10;
                                                             count1++;
                                                         }
                                                         else {
                                                             vc.view.frame = CGRectSetX(vc.view.frame, left2);
                                                             
                                                             [self.scrollView2 addSubview:vc.view];
                                                             left2 += 217 + 10;
                                                             count2++;
                                                         }
                                                     }];
                                                     
                                                     if (count1 > 0) {
                                                         self.scrollView1.contentSize = CGSizeMake(227 * count1 - 10, 101);
                                                     }
                                                     
                                                     if (count2 > 0) {
                                                         self.scrollView2.contentSize = CGSizeMake(227 * count2 - 10, 101);
                                                     }
                                                     [BCProgressHUD hideAnimated:YES];
                                                 } failure: ^(NSError *error) {
                                                     [BCProgressHUD hideWithError:error animated:YES];
                                                 }];
                               
                               } failure: ^(NSError *error) {
                                   [BCProgressHUD hideWithError:error animated:YES];
                               }];
                          }
      -(void)viewDidAppear:(BOOL)animated
      {
          [super viewDidAppear:animated];
          if (!USER_MANAGER.didLogin) {
              
              [BCLoginViewController checkLoggedInWithBlock:^(BOOL isLoggedIn) {
                  if (!isLoggedIn) {
                      [self.tabBarController setSelectedViewController:[self.tabBarController.viewControllers firstObject]];
                  }
              }];
          }
      }
      
      - (void)didReceiveMemoryWarning {
          [super didReceiveMemoryWarning];
          // Dispose of any resources that can be recreated.
      }
      
      - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
          if (nil == viewController) {
              return self.bannerViewControllers.firstObject;
          }
          NSInteger idx = [self.bannerViewControllers indexOfObject:viewController];
          NSParameterAssert(idx != NSNotFound);
          if (idx >= [self.bannerViewControllers count] - 1) {
              // we're at the end of the _pages array
              return self.bannerViewControllers[0];
          }
          // return the next page's view controller
          return self.bannerViewControllers[idx + 1];
      }
      
      - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
          if (nil == viewController) {
              return self.bannerViewControllers.firstObject;
          }
          NSInteger idx = [self.bannerViewControllers indexOfObject:viewController];
          NSParameterAssert(idx != NSNotFound);
          if (idx <= 0) {
              // we're at the end of the _pages array
              return self.bannerViewControllers.lastObject;
          }
          // return the previous page's view controller
          return self.bannerViewControllers[idx - 1];
      }
      
      - (void)pageViewController:(UIPageViewController *)viewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed {
          if (!completed) {
              return;
          }
          
          // Find index of current page
          
          NSUInteger indexOfCurrentPage = [self.bannerViewControllers indexOfObject:[viewController.viewControllers lastObject]];
          
          self.bannerPageControl.currentPage = indexOfCurrentPage;
      }
      
      @end
